<template>
  <div class="house-rental-container">
    <div class="page-header">
      <h2>房屋租赁</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchParams.name"
        placeholder="输入房屋编号/业主姓名搜索"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button type="success" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        添加租房
      </el-button>
      <el-button type="warning" @click="showRentDialog">
        <el-icon><House /></el-icon>
        房屋出租
      </el-button>
    </div>

    <!-- 房屋租赁列表 -->
    <el-table
      v-loading="loading"
      :data="houseRentalList"
      style="width: 100%"
      border
      stripe
    >
      <el-table-column prop="houseNum" label="房屋编号" width="120" />
      <el-table-column prop="cellName" label="小区名称" width="150" />
      <el-table-column prop="address" label="地址" min-width="200" />
      <el-table-column prop="ownerName" label="业主姓名" width="120" />
      <el-table-column prop="ownerPhone" label="业主电话" width="130" />
      <el-table-column prop="price" label="租金" width="100">
        <template #default="scope">
          {{ formatMoney(scope.row.price) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template #default="scope">
          {{ getTypeName(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            text
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            type="success"
            size="small"
            text
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            text
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="房屋租赁详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedHouse" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="房屋编号">
            {{ selectedHouse.houseNum }}
          </el-descriptions-item>
          <el-descriptions-item label="小区名称">
            {{ selectedHouse.cellName }}
          </el-descriptions-item>
          <el-descriptions-item label="地址">
            {{ selectedHouse.address }}
          </el-descriptions-item>
          <el-descriptions-item label="租金">
            {{ formatMoney(selectedHouse.price) }}
          </el-descriptions-item>
          <el-descriptions-item label="业主姓名">
            {{ selectedHouse.ownerName }}
          </el-descriptions-item>
          <el-descriptions-item label="业主电话">
            {{ selectedHouse.ownerPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedHouse.status)">
              {{ getStatusName(selectedHouse.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            {{ getTypeName(selectedHouse.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedHouse.remark || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button type="primary" @click="viewDialogVisible = false">
          关闭
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑房屋租赁"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="房屋编号" prop="houseNum">
          <el-input v-model="editForm.houseNum" placeholder="请输入房屋编号" />
        </el-form-item>
        <el-form-item label="小区名称" prop="cellName">
          <el-input v-model="editForm.cellName" placeholder="请输入小区名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="业主姓名" prop="ownerName">
          <el-input v-model="editForm.ownerName" placeholder="请输入业主姓名" />
        </el-form-item>
        <el-form-item label="业主电话" prop="ownerPhone">
          <el-input
            v-model="editForm.ownerPhone"
            placeholder="请输入业主电话"
          />
        </el-form-item>
        <el-form-item label="租金" prop="price">
          <el-input-number
            v-model="editForm.price"
            :precision="2"
            :min="0"
            placeholder="请输入租金"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="未出租" :value="1" />
            <el-option label="已出租" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input-number
            v-model="editForm.type"
            :min="0"
            placeholder="请输入类型"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="editForm.remark"
            placeholder="请输入备注"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加租房对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加租房"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="120px"
        :rules="addFormRules"
      >
        <el-form-item label="房屋ID" prop="houseId">
          <el-input-number
            v-model="addForm.houseId"
            :min="1"
            placeholder="请输入房屋ID"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="业主ID" prop="ownerId">
          <el-input-number
            v-model="addForm.ownerId"
            :min="1"
            placeholder="请输入业主ID"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="小区ID" prop="cellId">
          <el-input-number
            v-model="addForm.cellId"
            :min="0"
            placeholder="请输入小区ID"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="租金" prop="price">
          <el-input-number
            v-model="addForm.price"
            :precision="2"
            :min="0"
            placeholder="请输入租金"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="押付类型" prop="type">
          <el-select
            v-model="addForm.type"
            placeholder="请选择押付类型"
            style="width: 100%"
          >
            <el-option label="押一付一" :value="1" />
            <el-option label="押一付三" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addForm.remark"
            placeholder="请输入备注"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </template>
    </el-dialog>

    <!-- 房屋出租对话框 -->
    <el-dialog
      v-model="rentDialogVisible"
      title="房屋出租"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="rentFormRef"
        :model="rentForm"
        label-width="120px"
        :rules="rentFormRules"
      >
        <el-form-item label="选择房屋" prop="id">
          <el-select
            v-model="rentForm.id"
            placeholder="请选择要出租的房屋"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="house in houseRentalList.filter(h => h.status === 1)"
              :key="house.id"
              :label="`${house.cellName}-${house.houseNum} (${house.ownerName})`"
              :value="house.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="租户ID" prop="renterId">
          <el-input-number
            v-model="rentForm.renterId"
            :min="1"
            placeholder="请输入租户ID"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="rentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRent">确认出租</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElForm, ElMessageBox } from "element-plus";
import { Search, Plus, House } from "@element-plus/icons-vue";
import {
  getHouseRentalList,
  deleteHouseRental,
  updateHouseRental,
  addHouseRental,
  rentHouse
} from "@/api/houseRental";
import type { HouseRentalItem } from "@/api/houseRental";

// 搜索参数
const searchParams = ref({
  name: ""
});

// 加载状态
const loading = ref(false);

// 房屋租赁列表数据
const houseRentalList = ref<HouseRentalItem[]>([]);

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 查看详情对话框
const viewDialogVisible = ref(false);
const selectedHouse = ref<HouseRentalItem | null>(null);

// 编辑对话框
const editDialogVisible = ref(false);
const editFormRef = ref<InstanceType<typeof ElForm>>();
const currentEditId = ref<number | null>(null);

// 添加租房对话框
const addDialogVisible = ref(false);
const addFormRef = ref<InstanceType<typeof ElForm>>();

// 房屋出租对话框
const rentDialogVisible = ref(false);
const rentFormRef = ref<InstanceType<typeof ElForm>>();

// 编辑表单数据
const editForm = reactive({
  houseNum: "",
  cellName: "",
  address: "",
  ownerName: "",
  ownerPhone: "",
  price: 0,
  status: 1,
  type: 0,
  remark: ""
});

// 添加表单数据
const addForm = reactive({
  houseId: 0,
  ownerId: 0,
  cellId: 0,
  address: "",
  price: 0,
  type: 1,
  remark: ""
});

// 出租表单数据
const rentForm = reactive({
  id: 0,
  renterId: 0
});

// 表单验证规则
const formRules = {
  houseNum: [{ required: true, message: "请输入房屋编号", trigger: "blur" }],
  cellName: [{ required: true, message: "请输入小区名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  ownerName: [{ required: true, message: "请输入业主姓名", trigger: "blur" }],
  ownerPhone: [
    { required: true, message: "请输入业主电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  price: [{ required: true, message: "请输入租金", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 添加表单验证规则
const addFormRules = {
  houseId: [{ required: true, message: "请输入房屋ID", trigger: "blur" }],
  ownerId: [{ required: true, message: "请输入业主ID", trigger: "blur" }],
  cellId: [{ required: true, message: "请输入小区ID", trigger: "blur" }],
  address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  price: [{ required: true, message: "请输入租金", trigger: "blur" }],
  type: [{ required: true, message: "请选择押付类型", trigger: "change" }]
};

// 出租表单验证规则
const rentFormRules = {
  id: [{ required: true, message: "请选择房屋", trigger: "change" }],
  renterId: [{ required: true, message: "请输入租户ID", trigger: "blur" }]
};

// 查询房屋租赁列表
const fetchHouseRentalList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.currentPage - 1, // API 使用0索引
      limit: pagination.value.pageSize,
      name: searchParams.value.name
    };

    console.log("请求参数:", params);
    const response = await getHouseRentalList(params);
    console.log("API响应:", response);

    if (response.code === 0) {
      houseRentalList.value = response.data?.list || [];
      pagination.value.total = response.data?.total || 0;

      if (houseRentalList.value.length > 0) {
        ElMessage.success("获取房屋租赁列表成功");
      }
    } else {
      const errorMessage =
        response.message && response.message !== "操作成功"
          ? response.message
          : "获取房屋租赁列表失败，请检查网络连接或联系管理员";
      console.error("API返回错误:", errorMessage);
      ElMessage.error("获取房屋租赁列表失败：" + errorMessage);
      houseRentalList.value = [];
      pagination.value.total = 0;
    }
  } catch (error: any) {
    console.error("获取房屋租赁列表异常:", error);
    const errorMsg = error.message || "未知错误";
    ElMessage.error(`获取房屋租赁列表异常: ${errorMsg}，请稍后重试`);
    houseRentalList.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
  fetchHouseRentalList();
};

// 查看详情
const handleView = (row: HouseRentalItem) => {
  selectedHouse.value = row;
  viewDialogVisible.value = true;
};

// 显示添加对话框
const showAddDialog = () => {
  // 重置表单
  Object.assign(addForm, {
    houseId: 0,
    ownerId: 0,
    cellId: 0,
    address: "",
    price: 0,
    type: 1,
    remark: ""
  });
  addDialogVisible.value = true;
};

// 显示出租对话框
const showRentDialog = () => {
  // 重置表单
  Object.assign(rentForm, {
    id: 0,
    renterId: 0
  });
  rentDialogVisible.value = true;
};

// 保存添加
const saveAdd = async () => {
  if (!addFormRef.value) return;

  await addFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const response = await addHouseRental(addForm);

        if (response.code === 0) {
          ElMessage.success("添加成功");
          addDialogVisible.value = false;
          fetchHouseRentalList();
        } else {
          ElMessage.error(response.message || "添加失败");
        }
      } catch (error) {
        console.error("添加失败:", error);
        ElMessage.error("添加失败，请稍后重试");
      }
    }
  });
};

// 保存出租
const saveRent = async () => {
  if (!rentFormRef.value) return;

  await rentFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const response = await rentHouse(rentForm);

        if (response.code === 0) {
          ElMessage.success("出租成功");
          rentDialogVisible.value = false;
          fetchHouseRentalList();
        } else {
          ElMessage.error(response.message || "出租失败");
        }
      } catch (error) {
        console.error("出租失败:", error);
        ElMessage.error("出租失败，请稍后重试");
      }
    }
  });
};

// 编辑
const handleEdit = (row: HouseRentalItem) => {
  currentEditId.value = row.id;

  // 填充表单数据
  editForm.houseNum = row.houseNum || "";
  editForm.cellName = row.cellName || "";
  editForm.address = row.address || "";
  editForm.ownerName = row.ownerName || "";
  editForm.ownerPhone = row.ownerPhone || "";
  editForm.price = row.price || 0;
  editForm.status = row.status || 1;
  editForm.type = row.type || 0;
  editForm.remark = row.remark || "";

  editDialogVisible.value = true;
};

// 保存编辑
const saveEdit = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const updateData = {
          id: currentEditId.value!,
          price: editForm.price,
          type: editForm.type,
          remark: editForm.remark
        };

        const response = await updateHouseRental(updateData);

        if (response.code === 0) {
          ElMessage.success("修改成功");
          editDialogVisible.value = false;
          fetchHouseRentalList();
        } else {
          ElMessage.error(response.message || "修改失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败，请稍后重试");
      }
    }
  });
};

// 删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这条房屋租赁信息吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const response = await deleteHouseRental({ ids: [id] });

    if (response.code === 0) {
      ElMessage.success("删除成功");
      fetchHouseRentalList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (error.name !== "ElMessageBoxCancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  fetchHouseRentalList();
};

// 当前页码变更
const handleCurrentChange = (current: number) => {
  pagination.value.currentPage = current;
  fetchHouseRentalList();
};

// 获取状态标签类型
const getStatusTagType = (status: number): "success" | "warning" | "info" => {
  const statusMap: Record<number, "success" | "warning" | "info"> = {
    1: "success", // 未出租
    2: "warning" // 已出租
  };
  return statusMap[status] || "info";
};

// 获取状态名称
const getStatusName = (status: number): string => {
  const statusMap: Record<number, string> = {
    1: "未出租",
    2: "已出租"
  };
  return statusMap[status] || "未知状态";
};

// 获取类型名称
const getTypeName = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: "押一付一",
    3: "押一付三"
  };
  return typeMap[type] || "未知类型";
};

// 格式化金额
const formatMoney = (money?: number): string => {
  if (money === undefined || money === null) return "¥0.00";
  return `¥${money.toFixed(2)}`;
};

// 页面挂载时获取数据
onMounted(() => {
  fetchHouseRentalList();
});
</script>

<style scoped>
.house-rental-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-bar {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 400px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
}

.detail-content {
  padding: 20px 0;
}
</style>
